package ute.mvc.tiles.viewpreparer;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.tiles.Attribute;
import org.apache.tiles.AttributeContext;
import org.apache.tiles.preparer.ViewPreparer;
import org.apache.tiles.request.Request;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import ute.mvc.model.Course;
import ute.mvc.model.OpenCourse;
import ute.mvc.model.Subject;
import ute.mvc.model.User;

public class PortalHorizontalMenuPreparer implements ViewPreparer {

	@SuppressWarnings("unchecked")
	public void execute(Request request, AttributeContext attributeContext) {
		// TODO Auto-generated method stub
		HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest();
		HttpSession session = httpRequest.getSession();

		// Menu
		/*
		 * String requestAddress = httpRequest.getRequestURL().toString(); if
		 * (requestAddress.contains("/lecturer/")) type = 2; else if
		 * (requestAddress.contains("/portal/")) type = 1; else type = 3;
		 */
		// Work with session
		User user = (User) session.getAttribute("user");
		int type = user.getRole();
		
		attributeContext.putAttribute("type", new Attribute(type), true);
		
		attributeContext.putAttribute("user", new Attribute(user), true);
		if (type == 1) {
			// Get all course
			List<Course> courses = (List<Course>) session
					.getAttribute("courses");
			System.out.println(" Test" + courses.size());
			attributeContext.putAttribute("courses", new Attribute(courses),
					true);
			List<OpenCourse> lst = new ArrayList<OpenCourse>();
			lst.add(new OpenCourse());
			attributeContext.putAttribute("ocourses", new Attribute(lst),
					true);
		} else {
			// Get all opencourse with user id
			List<OpenCourse> courses = (List<OpenCourse>) session
					.getAttribute("courses");
			attributeContext.putAttribute("ocourses", new Attribute(courses),
					true);
			
			List<Course> lst = new ArrayList<Course>();
			lst.add(new Course());
			attributeContext.putAttribute("courses", new Attribute(lst),
					true);
		}
	}

}
